package com.siwei.mes.job;

import com.siwei.mes.common.util.DateHelper;
import com.siwei.mes.common.util.JsonUtils;
import com.siwei.mes.entity.ShxhSynchronizedata;
import com.siwei.mes.entity.UploadLaboratoryEntity;
import com.siwei.mes.entity.experiment.*;
import com.siwei.mes.entity.sync.tc.SupplyTask;
import com.siwei.mes.entity.sync.tc.Waybill;
import com.siwei.mes.entity.system.TestProjectInfo;
import com.siwei.mes.enums.CheckEnum;
import com.siwei.mes.enums.TestProjectEnum;
import com.siwei.mes.mapper.ExperimentCheckWaybillWeekMapper;
import com.siwei.mes.mapper.ShxhSynchronizedataMapper;
import com.siwei.mes.mapper.experiment.*;
import com.siwei.mes.mapper.system.TestProjectInfoMapper;
import com.siwei.mes.service.experiment.ExperimentMessageService;
import com.siwei.mes.sync.config.SyncProcessorService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.*;

/**
 * 定时清空对应按时间清理的关系表
 *
 * @Description: 定时清空对应按时间清理的关系表
 * @Version: 1.0
 * @author: mlchen
 * @date: 2025/3/10 14:40
 */
@Component
public class CleanExperimentCheckWaybillWeekJob {

    private static final Logger log = LoggerFactory.getLogger("job");
    @Resource
    private ExperimentCheckWaybillWeekMapper experimentCheckWaybillWeekMapper;
    @Resource
    private ExperimentMapper experimentMapper;
    @Resource
    private ExperimentDetailMapper experimentDetailMapper;
    @Resource
    private ExperimentWaybillMapper experimentWaybillMapper;
    @Resource
    private ExperimentSupplyTaskMapper experimentSupplyTaskMapper;
    @Resource
    private TestProjectInfoMapper testProjectInfoMapper;
    @Resource
    private ExperimentSampleSmokeMapper experimentSampleSmokeMapper;
    @Resource
    private ExperimentMessageService experimentMessageService;
    @Resource
    private SyncProcessorService syncProcessorService;
    @Resource
    private ShxhSynchronizedataMapper shxhSynchronizedataMapper;


    /**
     * 每周日23点59分59秒执行
     */
    @Scheduled(cron = "59 59 23 ? * SUN")
    public void cleanCheckWaybillWeekInfo() {
        log.info("当前时间：【{}】为周日，需要清空【pk_experiment_check_waybill_week】表中所有数据。如果没有两条委托需要补全数据！", DateHelper.getCurrentDate());
        List<ExperimentCheckWaybillWeek> checkWaybillWeekList = experimentCheckWaybillWeekMapper.selectAll();

        for (ExperimentCheckWaybillWeek checkWaybillWeek : checkWaybillWeekList) {

            Long firstExperimentId = checkWaybillWeek.getFirstExperimentId();
            if (firstExperimentId == null) {
                log.info("第一个试验委托id为空直接跳过");
                continue;
            }

            /**这边第一个委托永远不会为空的  因为生成第二个委托那边判断了是否有第一个委托 如果没有会补齐*/
            Long secondExperimentId = checkWaybillWeek.getSecondExperimentId();
            if (secondExperimentId == null) {
                /**第二个委托的代表数量  是第一个委托的代表数量*/
                Experiment experiment = experimentMapper.loadById(firstExperimentId);
                experiment.setId(null);
                experiment.erpInit(true);
                experiment.setEntrustTime(new Date());
                experimentMapper.insertSelective(experiment);

                Long experimentId = experiment.getId();//新的试验委托

                List<ExperimentDetail> experimentDetailList = experimentDetailMapper.selectByExperimentId(firstExperimentId, null);
                Set<String> testProjectCodeList = new HashSet<>();
                for (ExperimentDetail experimentDetail : experimentDetailList) {
                    testProjectCodeList.add(experimentDetail.getTestProjectCode());
                }


                /**生成对应试验台账详情信息*/
                List<ExperimentDetail> detailList = new ArrayList<>();
                /**查询所有试验项目信息*/
                List<TestProjectInfo> testProjectInfoList = testProjectInfoMapper.selectByTestProjectCodeList(testProjectCodeList);
                for (TestProjectInfo testProjectInfo : testProjectInfoList) {
                    ExperimentDetail detail = new ExperimentDetail();
                    detail.setExperimentId(experiment.getId());
                    detail.setCheckType(CheckEnum.BATCH.getCode());
                    detail.tcInit(true);
                    detail.setTestProjectCode(testProjectInfo.getTestCode());
                    detail.setTestProjectName(testProjectInfo.getTestName());
                    detail.setObjJson(testProjectInfo.getObjJson());
                    /**如果是粗骨料筛分析，需要重新组装json*/
                    if (testProjectInfo.getTestCode().equals(TestProjectEnum.COARSE_AGGREGATE_PARAM_CGL_SFX.getCode())) {
                        detail.setSfxJson(experiment, detail);
                    }
                    detailList.add(detail);
                }
                if (!detailList.isEmpty()) {
                    experimentDetailMapper.insertList(detailList);
                }

                /**新增对应快检的抽样信息 */
                for (TestProjectInfo testProjectInfo : testProjectInfoList) {
                    ExperimentSampleSmoke sampleSmoke = new ExperimentSampleSmoke();
                    sampleSmoke.setId(null);
                    sampleSmoke.tcInit(true);
                    sampleSmoke.setExperimentId(experiment.getId());
                    sampleSmoke.setSampleTime(new Date());
                    sampleSmoke.setIsTestBlock(0);// 是否是试块 1-是 0-不是
                    sampleSmoke.setSamplePersonName(experiment.getEntrustPersonName());
                    sampleSmoke.setDisposerPersonName(experiment.getEntrustPersonName());
                    sampleSmoke.setTestProjectCode(testProjectInfo.getTestCode());
                    sampleSmoke.setTestProjectName(testProjectInfo.getTestName());
                    sampleSmoke.setSampleUse(testProjectInfo.getTestName());
                    if (-1 != testProjectInfo.getSampleQuantity()) {
                        sampleSmoke.setSampleQuantity(testProjectInfo.getSampleQuantity());
                    }
                    experimentSampleSmokeMapper.insertSelective(sampleSmoke);
                }

                /**试验委托和运单关联*/
                List<Waybill> waybillList = experimentWaybillMapper.selectByExperimentId(firstExperimentId);
                for (Waybill waybill : waybillList) {
                    experimentWaybillMapper.insertSelective(new ExperimentWaybill().setExperimentId(experimentId).setWaybillId(waybill.getId()).setBehalfNumber(waybill.getBehalfNumber()));
                }

                /**试验委托和供货任务关联*/
                List<SupplyTask> supplyTaskList = experimentSupplyTaskMapper.selectByExperimentId(firstExperimentId);
                for (SupplyTask supplyTask : supplyTaskList) {
                    ExperimentSupplyTask experimentSupplyTask = new ExperimentSupplyTask().setExperimentId(experimentId).setSupplyTaskId(supplyTask.getId());
                    experimentSupplyTask.setCreateTime(new Date());
                    experimentSupplyTask.setReadTime(null);
                    experimentSupplyTaskMapper.insertSelective(experimentSupplyTask);

                    /**这里新增任务单的关联关系 给对应试验委托的isNewTask改为1*/
                    log.info(this.getClass().getName() + "新增任务单给对应isNewTask修改为1");
                    experimentMapper.updateIsNewTask(experimentId, 1);

                    log.info(this.getClass().getName() + "新增任务单之后，推送协会！");
                    /**推送到协会，这里新增任务单 状态为自动上传*/
                    /**这里判断是否已经上传到协会，如果没有上传到协会就不推送*/
                    ShxhSynchronizedata shxhSynchronizedata = shxhSynchronizedataMapper.selectByExperimentIdOne(experimentId);
                    if (shxhSynchronizedata != null && shxhSynchronizedata.getSampleId() != null) {
                        log.info(this.getClass().getName() + "推送到协会！");
                        syncProcessorService.submitRequest(new UploadLaboratoryEntity().setExperimentId(Collections.singletonList(String.valueOf(experimentId))).setUploadState(1));
                    }
                }

                /**新增试验台账消息通知记录*/
                experimentMessageService.saveExperimentMessage(experiment);
                log.info("补偿第二个试验委托成功，来源试验委托id：【{}】，第二次试验委托id：【{}】", firstExperimentId, experimentId);
            }

            experimentCheckWaybillWeekMapper.deleteByPrimaryKey(checkWaybillWeek.getId());
            log.info("定时任务清空【pk_experiment_check_waybill_week】表中数据完成！清空数据：【{}】", JsonUtils.getJson(checkWaybillWeek));
        }
    }
}
